<!--
 * @Author: Mcc
 * @Date: 2024-07-30 16:13:56
 * @LastEditors: 王明明834578987 10266004+wang-mingming-834578987@user.noreply.gitee.com
 * @LastEditTime: 2024-10-08 14:23:00
 * @FilePath: \ft-apply-admin-apply-pro\src\views\ApplicationList\applicationList.vue
 * @Description:
 *
 * Copyright (c) 2024 by Mcc, All Rights Reserved.
-->
<template>
  <div id="applicationList">
    <div class="main-content">
      <div class="search">
        <div class="titles">
          <span class="title">应聘列表</span>
          <!-- <span>最近更新：2021/05/29 18:04:39</span>
          <span class="update">更新</span>-->
        </div>
        <div class="search-r">
          <span class="flex">
            <a-radio-group v-model:value="radiogroupValue" class="abnormal" name="radioGroup">
              <a-radio :class="['abnormal-item', radiogroupValue === item.key ? `child${idx + 1}` : '']"
                @change="handleAbnormalChange(item)" :value='item.key' v-for="(item, idx) in plainOptions">
                {{ item.text }}
              </a-radio>
            </a-radio-group>
            <a-input class="search-input" v-model:value="keyWords" placeholder="输入姓名或手机号搜索"
              @pressEnter="searchKeyWords">
              <template #suffix>
                <img class="search-i-i" @click="searchKeyWords" src="@/assets/icon/search.svg">
              </template>
            </a-input>
            <Button class="search-b-r reset-btn" :loading="loading" @click="removeAll">重置
              <template #icon><img class="search-i-r" src="@/assets/icon/reset.svg"></template>
            </Button>
          </span>

          <!-- <a-upload class="upload-list-inline" :before-upload="fileUpResumesList" :showUploadList="false">
            <Button v-auth="'exportResume'" class="search-b-r" :loading="loading">导入表格
              <template #icon><upload-outlined></upload-outlined></template>
            </Button>
          </a-upload> -->
          <span>
            <Button class="search-b-r" color="#209EE4"
              @click="$router.push({ path: '/ApplicationList/Join', query: {} })">新增简历
              <template #icon><img class="search-i" src="@/assets/icon/add.svg"></template>
            </Button>
            <Button v-auth="'exportResume'" color="#36AF5C" class="search-b-r" :loading="loading"
              @click="getTabulationExport">导出表格
              <template #icon><img class="search-i" src="@/assets/icon/export.svg"></template>
            </Button>
            <Button v-auth="'exportResume'" color="warning" class="search-b-r" @click="show = true">一键导入
              <template #icon><img class="search-i" src="@/assets/icon/upload.svg"></template>
            </Button>
          </span>

        </div>
      </div>
      <div>
        <a-spin :spinning="statusLoading">
          <div class="bottom_table">
            <div class="result-wrap">
              <div class="inner" v-show="resultList.length > 0">
                <span v-for="item in resultList" class="result-item">
                  {{ item.value }}
                  <CloseOutlined @click="remove(item)" />
                </span>
                <span @click="removeAll" class="result-clear">清空条件</span>
              </div>
            </div>

            <BasicTable ref="tableRef" :scroll="{ y: height }" rowKey="id" @register="registerTable" size="small">
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'educationType'">
                  <a-button class="graduate" :class="{ 'graduate-other': record.educationType == '1' }">
                    {{ record.graduateTime ? record.graduateTime : record.educationType == '0' ? '应届生' : '往届生' }}
                  </a-button>
                </template>
                <template v-if="column.dataIndex === 'recommendsName'">
                  {{ record.recommendsName || '无' }}
                </template>
                <template v-if="column.dataIndex === 'examineUser'">
                  {{ record.examineUser?.map(item => item?.userName).join('、') || '无' }}
                </template>
                <template v-if="column.dataIndex === 'trainingUser'">
                  {{ record.trainingUser?.map(item => item?.userName).join('、') || '无' }}
                </template>
                <template v-if="column.key === 'name'">
                  <span class="status-name child1" v-if="record.isRecommends === '0'">内</span>
                  <span class="status-name child2" v-if="record.isException === '1'">异</span>
                  <span class="status-name child3" v-if="record.sendCount > 1">{{ record.sendCount }}</span>
                  <span class="user-name" @click="goApplicationDetail(record)">{{ record.name }}</span>
                </template>
                <template v-if="column.key === 'action'">
                  <a-button style="margin:0 3px" v-auth="'offlineInterview'"
                    v-if="['jldsx', 'msdym', 'msdms'].includes(route.name) && (record.status === 'RESUME_SCREENING_IN_PROGRESS' || record.status === 'INTERVIEW_SCHEDULED' || record.status === 'ARRIVAL_SCHEDULED')"
                    @click="getOfflineInterviewTypeList([record.id])" type="primary">
                    线下到面</a-button>
                  <span v-auth="'cancelOfflineInterview'"
                    v-if="['msdms'].includes(route.name) && record.status === 'INTERVIEW_IN_PROGRESS'"
                    class="user-name " :class="[record.interviewType == '线上面试' ? 'prevent' : '']"
                    @click="getOnlineInterviewType(record)" type="primary">
                    取消线下</span>
                  <!-- :disabled="" -->
                  <span v-if='false'>
                    <Button style="margin:0 3px" v-auth="'resumesProgress'" color="success"
                      @click="pass(record)">通过</Button>
                    <Button style="margin:0 3px" v-auth="'resumesEliminate'" color="error"
                      @click="dieOut(record)">淘汰</Button>
                  </span>


                  <a-button v-auth="'appointmentTraining'"
                    v-if="['pxdy'].includes(route.name) && record.status === 'TRAINING_SCHEDULED'"
                    @click.stop="interviewSession(record)" type="primary"
                    style="background-color: #36AF5C">预约培训</a-button>
                  <template v-if="route.name === 'pxdp'">
                    <a-button v-auth="'sendTrainingMail'" type="primary" @click="sendTrainSession(record, 'fsyj')"
                      v-if="record.status === 'TRAINING_EMAIL_SENT'">发送培训邮件</a-button>
                    <span v-auth="'sendTrainingMail'" v-else-if="record.status === 'TRAINING_ARRIVAL_SCHEDULED'"
                      @click="sendTrainSession(record, 'cfyx')" class="user-name">重发邮件</span>
                  </template>
                  <a-button v-auth="'completeThird'"
                    v-if="route.name === 'qydqsf' && record.status === 'CONTRACT_SIGNED'" @click="sendSession(record)"
                    type="primary">完成三方</a-button>
                  <a-button v-auth="'waitEntryByDeatil'"
                    v-if="route.name === 'rzdrz' && record.status === 'ONBOARDING_IN_PROGRESS'"
                    @click.stop="entrySession(record)" type="primary">入职</a-button>
                  <a-button v-auth="'probation'"
                    v-if="route.name === 'rzsxz' && record.status === 'INTERNSHIP_IN_PROGRESS'"
                    @click.stop="entryOnSession(record, 'zrsy')" type="primary">转入试用</a-button>
                  <a-button v-auth="'confirmed'"
                    v-if="route.name === 'rzsyq' && record.status === 'PROBATION_IN_PROGRESS'"
                    @click.stop="entryOnSession(record, 'zz')" type="primary">转正</a-button>
                </template>
                <template v-if="column.key === 'interviewType'">
                  <a-button v-if="['mstt', 'msdms'].includes(route.name) && record.interviewType" class="interview"
                    :class="{ 'interview-other': record.interviewType == '线下' }" size="small" type="primary">
                    {{ record.interviewType?.replace("面试", "") }}</a-button>
                </template>
              </template>
              <template
                #customFilterDropdown="{ setSelectedKeys, selectedKeys, confirm, visible, clearFilters, column }">
                <div style="padding: 8px;min-width: 270px;" v-if="Object.keys(state).length > 0">
                  <div class="filter-dropdown" v-if="state[column.key]">
                    <div v-if="column.formType === 'input'">
                      <a-input v-model:value="state[column.key].inputValue" :placeholder="state[column.key].placeholder"
                        @blur='handleBlur(column)' @focus='handleFocus(column)'>
                        <template #prefix>
                          <SearchOutlined />
                        </template>
                      </a-input>
                      <div v-if="column.history" v-show="column.showHistory" class="history-wrap">
                        <div v-show="column.historyList?.length > 0" class="history-wrap-item"
                          @click="state[column.key].inputValue = v" v-for="v in column.historyList">
                          <span>{{ v }} </span>
                          <i class="iconfont icon-guanbi" @click.stop.prevent="removeHistory(column, v)"></i>
                        </div>
                        <div style="color:#bbb ;" v-show="column.historyList?.length === 0">
                          暂无数据
                        </div>
                      </div>

                    </div>
                    <div v-else-if="column.formType === 'time'">
                      <div class="flex" style="margin-bottom: 16px;cursor: pointer">
                        <span @click="sortChange(column, 'asc', confirm)"
                          :style="{ color: state[column.key].sort === 'asc' ? '#209EE4' : '' }">
                          <ArrowUpOutlined />正序
                        </span>
                        <span @click="sortChange(column, 'desc', confirm)"
                          :style="{ color: state[column.key].sort === 'desc' ? '#209EE4' : '' }">
                          <ArrowDownOutlined />倒序
                        </span>
                      </div>
                      <a-range-picker date-format="YYYY年M月D日" time-format="HH:mm:ss" format="YYYY年M月D日"
                        value-format="YYYY-MM-DD" v-model:value="state[column.key].timeRange"
                        :placeholder="['开始时间', '结束时间']" style="width: 100%"></a-range-picker>
                    </div>
                    <div style="margin-bottom: 2px" v-else-if="column.formType === 'select'">
                      <div class="reset-top">
                        <a-input :style="{ width: column.otherFormType === 'sort' ? '' : '100%' }"
                          v-if="column.otherFormType === 'search' || column.otherFormType === 'sort'"
                          class="reset-input" ref="searchInput" :placeholder="`搜索 ${column.title}`"
                          :value="state[column.key].searchText" @change="handleInputChange($event, column)">
                          <template #prefix>
                            <SearchOutlined />
                          </template>
                        </a-input>
                        <div class="flex" v-if="column.otherFormType === 'sort'" style="cursor: pointer">
                          <span style="margin-right: 2px" @click="sortChange(column, 'asc', confirm)"
                            :style="{ color: state[column.key].sort === 'asc' ? '#209EE4' : '' }">
                            <ArrowUpOutlined />正序
                          </span>
                          <span @click="sortChange(column, 'desc', confirm)"
                            :style="{ color: state[column.key].sort === 'desc' ? '#209EE4' : '' }">
                            <ArrowDownOutlined />倒序
                          </span>
                        </div>
                      </div>
                      <div>
                        <Checkbox style="margin-bottom: 8px;" v-model:checked="state[column.key].checkAll"
                          :indeterminate="state[column.key].indeterminate" @change="onCheckAllChange(column)">
                          全选
                        </Checkbox>
                        <div style="" v-if="state[column.key].options.length > 0">
                          <CheckboxGroup class='boxGroup' v-model:value="state[column.key].checkedList"
                            :options="state[column.key].options" @change="onCheckChange(column)" />
                        </div>
                      </div>
                    </div>
                  </div>
                  <div style="display: flex;justify-content: space-between;margin-top: 10px;">
                    <a-button type="text" style="color: #209EE4" size="small" @click="handleReset(column)">
                      清除所选内容
                    </a-button>
                    <a-button type="primary" size="small" @click.native="handleSearch(selectedKeys, confirm, column)">
                      确定
                    </a-button>
                  </div>
                </div>
              </template>
            </BasicTable>
            <div
              v-show="['msdym', 'msdms', 'pxdy', 'pxdp', 'pxpxz', 'pxdlq', 'qydqyy', 'qydqsf', 'rzdrz', 'rzsxz', 'rzsyq', 'rzyzz', 'jldsx', 'msdym', 'msdms'].includes(route.name)"
              v-if="tableData.length > 0" class="table_btnC">
              <a-checkbox v-model:checked="allchecked" @click="selectAllRows">全选</a-checkbox>
              <a-button v-auth="'batchAssign'" :style="{ color: getSelectRows().length > 0 ? '#209eff' : '' }"
                v-show="['msdym', 'msdms', 'pxdy', 'pxdp', 'pxpxz', 'pxdlq', 'qydqyy', 'qydqsf', 'rzdrz', 'rzsxz', 'rzsyq', 'rzyzz',].includes(route.name)"
                class="btn" size='default' @click="batchOperation">批量指派</a-button>
              <a-button v-auth="'batchOfflineInterview'" v-show="['jldsx', 'msdym', 'msdms'].includes(route.name)"
                class="btn" style="margin-left: 10px;" size='default' @click="offlineInterviews">线下到面</a-button>
              <a-button v-auth="'batchOfflineInterview'" v-show="['jldsx'].includes(route.name)" class="btn"
                style="margin-left: 10px;" size='default' @click="batchPass">批量通过</a-button>
            </div>
          </div>
        </a-spin>
      </div>
    </div>
    <!--预约培训-->
    <yypxModal ref="modal" @onSuccess="reload()"></yypxModal>
    <!--入职-->
    <EntryModal ref="entryModal" @onSuccess="reload()"></EntryModal>
    <!--转入试用、转正-->
    <EntryOnTrial ref="entryOnModal" @onSuccess="reload()"></EntryOnTrial>
    <!--三方-->
    <ContractSecondInterview ref="secondModal" @onSuccess="reload()"></ContractSecondInterview>
    <!--批量指派-->
    <BatchModal ref="batchModalRef" @onSuccess="reload()"></BatchModal>
    <!--发送邮件-->
    <SendTrainMailModal ref="sendTrainModal" @onSuccess="reload()"></SendTrainMailModal>
    <Modal :open="tipsModalOpen" title="提示" :footer="null" @cancel="tipsModalOpen = false">
      <div style="padding: 20px 0" v-html="tipsModalContent"></div>
    </Modal>
    <BasicModal :show="show" title="一键导入" width="30%" @closeModal="show = false; uploadFileList = []"
      :widthComfirm="true" @comfirm='uploadConfirm'>
      <template #content>
        <div class="upload-dragger">
          <a-upload-dragger accept=".xlsx,.csv" v-model:file-list="uploadFileList"
            :before-upload="() => { uploadFileList = []; return false }">
            <p class="ant-upload-drag-icon">
              <CloudUploadOutlined />
            </p>
            点击上传
            <template #itemRender="{ file, actions }">
              <div class="item-render">
                <span>
                  <PaperClipOutlined style="margin-right:5px;" />{{ file.name }}
                </span>
                <span>
                  <a href="javascript:;" style="color:#333" @click="actions.remove">
                    <CloseSquareOutlined />
                  </a>
                </span>
              </div>
            </template>
          </a-upload-dragger>
        </div>
        <span class="download-btn" @click="downloadTemplate">
          <img src="../../assets/icon/xlsx.svg">
          下载表格模板
        </span>
      </template>
    </BasicModal>

  </div>
</template>
<script lang="ts">//动态设置组件名称
import { defineComponent, nextTick } from 'vue';
let name = ''
const getLastPathSegment = () => {
  const url = window.location.hash; // 获取 URL 中的 hash 部分（包括 #）
  const pathSegments = url.split('/'); // 根据 '/' 分割
  return pathSegments[pathSegments.length - 1] || ''; // 返回最后一段路径
};
name = getLastPathSegment()
export default defineComponent({
  name: name,
});
</script>

<script lang="ts" setup>
const loading = ref<boolean>(false)
const statusLoading = ref<boolean>(false);
import { comStores } from "../../store/common/comStore";
import { downloadByData } from '@/utils/file/download';
import { useRoute, useRouter } from "vue-router";
import { Button } from '@/components/Button'
import { h, ref, computed, onMounted, onActivated } from 'vue';
import { Checkbox, CheckboxGroup, message, Modal } from 'ant-design-vue';
import { useTable } from "../../components/Table";
import { useModal } from '@/components/Modal';
import yypxModal from "./components/yypxModal.vue";
import EntryModal from "./components/EntryModal.vue";
import EntryOnTrial from "./components/EntryOnTrial.vue";
import ContractSecondInterview from "./components/ContractSecondInterview.vue";
import BatchModal from "./components/BatchModal.vue";
import SendTrainMailModal from "./components/SendTrainMailModal.vue";
import { resumeProgress, offlineInterviewType } from "@/api/application-details/index.ts";
import BasicModal from "@/views/ApplicationDetails/Modals/BasicModal.vue"
import { getSuffix } from "@/assets/common/common.ts";
const store = comStores();
const { userInFor } = store;
const route = useRoute();
const router = useRouter();
// 导入API
import {
  tabulationPage,
  tabulationResumePage,
  tabulationInterviewPage,
  tabulationTrainPage,
  tabulationSigningPage,
  tabulationEntryPage,
  selectCommonConfig, selectCommonConfigDetail, offlineInterviewTypeList, tabulationExport, onlineInterviewType,
  fileUpResumesListPc,
  batchResumeProgress
} from '@/api/applay/applicationList/self'
// 表格下拉框接口
import getSelectApi from "@/api/applay/applicationList/self.ts";
// 表头 以及下拉框配置化
import {
  otherColumns,
  selectOptions,
  navStatusType
} from './components/data.ts';
const tipsModalOpen = ref(false)
const tipsModalContent = ref('')
const tableColumns = ref({});
const radiogroupValue = ref<any>("")
const uploadFileList = ref<any>([]);
const plainOptions = ref<any>([
  { key: 'isRecommends', text: '内推', value: false, default: ['0'] },
  { key: 'abnormal', text: '异常', value: false, default: '1' },
  { key: 'isRepeated', text: '复投', value: false, default: 'Y' },
])
const height = computed(() => {
  const scrollHeight = document.documentElement.scrollHeight;
  const ratio = (630 - (resultList.value.length > 0 ? 30 : 0) )/ 962
  return scrollHeight * ratio
})
/*
* 因为是多页面公用一个文件 所以通过路由配置的方式 去加载不同的表头配置
* */
tableColumns.value = otherColumns[route.name]
// 过滤表格数据
function unique(arr, requestType) {
  const res = new Map();
  let list = arr.filter((a) => !res.has(a.label) && res.set(a.label, 1))
  if (requestType == '2') {
    list = list.filter(el => el.label != '小低' && el.label != '小高')
  }
  return list
}
// 初始化获取下拉框数据
const getOptions = async (item: any) => {
  let temp = {}
  if (item.requestApi === 'selectUserByRole') {
    temp = {
      request: item.requestType,
      type: 0
    }
  } else if (item.requestApi === 'selectCommonConfig') {
    temp = {
      type: 1,
      level: item.requestType
    }
  } else if (item.requestApi === 'selectCommonConfigDetail') {
    temp = { type: item.requestType }
  } else if (item.requestApi === 'tabulationStatusList') {
    temp = {
      type: navStatusType[route.name].type,
      process: navStatusType[route.name].process,
    }
  }
  const data = await getSelectApi[item.requestApi](temp);
  const list = data.data.map((el) => {
    return {
      label: el.label || el,
      value: el.value || el,
    };
  });
  return unique(list, item.requestType)
}
const selectOptionsList = ref()
selectOptionsList.value = selectOptions
// 遍历下拉框的配置化 并且给下拉框下拉数据进行接口赋值
Object.keys(selectOptionsList.value).forEach(async (key) => {
  if (selectOptionsList.value[key]?.requestApi) {
    selectOptionsList.value[key].option = await getOptions(selectOptionsList.value[key])
  }
})
// 全局状态换成
const state = ref<any>({});
// 设置表头的下拉数据 主要用于v-modal
const setTableHeader = () => {
  for (let i = 0; i < tableColumns.value.length; i++) {
    state.value[tableColumns.value[i].key] = {}
    state.value[tableColumns.value[i].key].formType = tableColumns.value[i].formType
    if (tableColumns.value[i].formType === 'select') {
      state.value[tableColumns.value[i].key].options = selectOptionsList.value[tableColumns.value[i].key] ? selectOptionsList.value[tableColumns.value[i].key].option : []
      state.value[tableColumns.value[i].key].cacheOptions = selectOptionsList.value[tableColumns.value[i].key] ? selectOptionsList.value[tableColumns.value[i].key].option : []
      if (tableColumns.value[i]?.field) {
        selectOptionsList.value[tableColumns.value[i].key].field = tableColumns.value[i].field
      }
      if (tableColumns.value[i].key === 'interviewOfficer' ||tableColumns.value[i].key === 'operators' ) {
        state.value[tableColumns.value[i].key].options = state.value[tableColumns.value[i].key].options.map(el => {
          return {
            label: el.label,
            value: el.label
          }
        })
        state.value[tableColumns.value[i].key].cacheOptions = state.value[tableColumns.value[i].key].options.map(el => {
          return {
            label: el.label,
            value: el.label
          }
        })
      }
    } else if (tableColumns.value[i].formType === 'input') {
      state.value[tableColumns.value[i].key].inputValue = ''
    } else if (tableColumns.value[i].formType === 'time') {
      // state.value[tableColumns.value[i].key].timeRange = []
      state.value[tableColumns.value[i].key].timeParams = tableColumns.value[i].timeParams
    }
    state.value[tableColumns.value[i].key].placeholder = selectOptionsList.value[tableColumns.value[i].key] ? selectOptionsList.value[tableColumns.value[i].key].placeholder : ''
  }
}
setTableHeader()


const totalCount = 1300;
// 定义接口请求参数
const params = ref({
  type: undefined,
  education: undefined,
  sex: undefined,
  interpolate: undefined,
  school: undefined,
  region: undefined,
  action: undefined,
  plane: undefined,
  maintain: undefined,
  interview: undefined,
  interviewer: undefined,
  time: []
})
const show = ref<boolean>(false)
// 下拉框筛选结果集
const resultList = ref<any>([]);
const filterFlag = ref<boolean>(false);
const [registerModal, { openModal: openModal }] = useModal();
const [batchModal, { openModal: batchOpenModal }] = useModal();
const stages = [
  { name: '简历环节', count: 1600000 },
  { name: '面试环节', count: 160000 },
  { name: '培训环节', count: 16000 },
  { name: '签约环节', count: 1600 },
  { name: '入职环节', count: 160 }
];
const statusOptions = [
  { label: '待入职', value: '1' },
  { label: '实习中', value: '2' },
  { label: '试用期', value: '3' },
  { label: '已转正', value: '4' },
  { label: '淘汰', value: '5' },
  { label: '放弃', value: '6' },
  { label: '离职', value: '7' }
];
/*预约培训*/
const modal = ref()
const interviewSession = (item: Object) => {
  modal.value.open({
    info: item
  })
}
/*入职*/
const entryModal = ref()
const entrySession = (item: Object) => {
  entryModal.value.open({
    info: item
  })
}
/*转入试用*/
const entryOnModal = ref()
const entryOnSession = (item: Object, type: String) => {
  entryOnModal.value.open({
    info: item,
    type
  })
}
/*完成三方*/
const secondModal = ref()
const sendSession = (item: Object) => {
  secondModal.value.open({
    info: item
  })
}

/*发送邮件*/
const sendTrainModal = ref()
const sendTrainSession = (item: Object, type: String) => {
  sendTrainModal.value.open({
    info: item,
    type
  })
}
/*批量指派*/
const batchModalRef = ref()
const batchOperation = (item: Object) => {
  let selects = getSelectRows();
  const routeName: string = route.name as string;
  if (selects.length > 0) {
    const resumeIds = selects.map(item => {
      return {
        id: item.id,
        name: ['msdms'].includes(routeName) ? item.interviewer : item.preserveUserName
      }
    })
    batchModalRef.value.open({
      resumeIds,
      type: ['msdms'].includes(routeName) ? 'msg' : ['pxdy', 'pxdp', 'pxpxz', 'pxdlq', 'qydqyy', 'qydqsf', 'rzdrz', 'rzsxz', 'rzsyq', 'rzyzz'].includes(routeName) ? 'whhr' : 'ymhr'
    })
  } else {
    message.error('你还没选择数据');
  }
}
const closeModal = () => {
  console.log('===>closeModal')
  modal.value.open()
}
const allchecked = ref(false); // 全选
const isAllSelected = ref(true); // 控制是否全选
const selectedIndex = ref(-1); // 初始化为-1，表示没有选中任何项
const statusIndex = ref();
// 表格的数据
const tableData = ref([]);
// 定义一个全局请求的参数 最终进行参数组装
const requestPageData = ref(); // 是表格自带的分页请求参数信息
const diyRequestData = ref({}); // 是自定义的请求参数
const filterRequestData = ref({
  abnormal: null,   //0正常，1异常
  isRepeated: null,  //Y:N  //Y单次 N多次
  isRecommends: null, //isRecommends[0：内推，1不是内推]
})

const handleAbnormalChange = (item) => {
  plainOptions.value.forEach(el => {
    if (el.key == item.key) {
      filterRequestData.value[el.key] = el.default
    } else {
      filterRequestData.value[el.key] = null
    }
  })
  reload(gerRequestParames())
}
const getTabulationPage = (parames: any) => {
  requestPageData.value = parames;
  if (route.name === 'all') {
    return tabulationPage(gerRequestParames())
  } else if (route.meta.parentName === 'jl') {
    return tabulationResumePage(gerRequestParames())
  } else if (route.meta.parentName === 'ms') {
    return tabulationInterviewPage(gerRequestParames())
  } else if (route.meta.parentName === 'px') {
    return tabulationTrainPage(gerRequestParames())
  } else if (route.meta.parentName === 'qy') {
    return tabulationSigningPage(gerRequestParames())
  } else if (route.meta.parentName === 'rz') {
    return tabulationEntryPage(gerRequestParames())
  }
  return tabulationPage(gerRequestParames())
}
// 导出
const getTabulationExport = async () => {
  const data = await tabulationExport(gerRequestParames())
  await downloadByData(data, route.matched.map(item => item.meta.title).join('-'));
  message.success("下载成功")
}
// 请求参数
const gerRequestParames = () => {
  const req: any = {
    ...diyRequestData.value, // 自定义请求
    ...getTableHeaderRequest(), // 表头筛选
    ...requestPageData.value, // 基础请求
    ...navStatusType[route.name], // 路由请求
    ...filterRequestData.value //顶部筛选项
  }
  // const req: any = parames
  return req
}
// 从表头下拉中获取数据
const getTableHeaderRequest = () => {
  const obj = {}
  Object.keys(state.value).forEach((i: any) => {
    if (state.value[i].formType === 'select' && state.value[i].checkedList && state.value[i].checkedList.length > 0) {
      // 如果是下拉框的话
      obj[i] = state.value[i].checkedList
    } else if (state.value[i].formType === 'input' && state.value[i].inputValue) {
      // 如果是输入框的话
      obj[i] = state.value[i].inputValue
    } else if (state.value[i].formType === 'time' && state.value[i].timeRange) {
      obj[state.value[i].timeParams[0]] = state.value[i].timeRange[0]
      obj[state.value[i].timeParams[1]] = state.value[i].timeRange[1]
    }
  })
  return obj
}
// Reload状态
const pageReloadStatus = ref(false);
// 表格请求
const [registerTable, { reload, setPagination, getForm, getPaginationRef, getSelectRows, setSelectedRowKeys, clearSelectedRowKeys, updateTableData, getDataSource }] = useTable({
  title: '',
  // dataSource: tableData,
  api: getTabulationPage,
  columns: tableColumns,
  formConfig: {
    labelWidth: 120,
    //schemas: searchFormSchema,
    autoSubmitOnEnter: true,
    showAdvancedButton: true,
    autoAdvancedLine: 4,
    showSubmitButton: false,
  },
  pagination: {
    pageSize: 50, // 设置每页显示 50 条数据
    // 可以添加更多 pagination 的配置
  },
  rowSelection: {
    type: 'checkbox',
    getCheckboxProps(record) {
      // Demo: 第一行（id为0）的选择框禁用
      if (record.status === 2) {
        return { disabled: true };
      } else {
        return { disabled: false };
      }
    },
  },
  clearSelectOnPageChange: true,
  clickToRowSelect: false,
  useSearchForm: false,
  showTableSetting: false,
  showIndexColumn: false,
  bordered: true,
  canResize: true,
  beforeFetch(info) {

  },
  sortFn(sortInfo) {

  },
  afterFetch(list) {
    // 表格请求完成后的一些处理
    if (getSelectRows().length === 0) {
      // 每次请求重置全选
      allchecked.value = false
    }
    // 缓存一份表格结果
    tableData.value = list
    if (!pageReloadStatus.value) {
      pageReloadStatus.value = true
      // 设置表头信息
      setTableHeader()
    }
    store.getMenuCountList()
  }
});
onActivated(async () => {
  console.log('onActivated is invoke')
  reload(gerRequestParames())
})
onMounted(() => {
  console.log('onMounted is invoke')
})
// 上传
const fileData = ref()
const fileUpResumesList = (file: any) => {
  console.log('fileUpResumesList', file)
  const formData = new FormData();
  formData.append('file', file)
  console.log('formData', formData)
  fileUpResumesListPc(formData).then(res => {
    console.log('res', res)
    if (res.code === '10001') {
      if (!res.data) {
        message.error({
          content: res.msg || '系统异常',
          duration: 4
        });
        return
      }
      let content = '<div style="white-space: normal;"><div style="padding-bottom: 6px">导入失败，部分数据已存在，请修改表格后重新上传</div>';
      // 使用 forEach 或 for 循环拼接 HTML
      res.data.forEach((item) => {
        content += `<div>${item.userName} ${item.phone}</div>`; // 动态生成每个项
      });
      content += '</div>';
      tipsModalContent.value = content
      tipsModalOpen.value = true
    } else if (res.code === '10000') {
      message.success({
        content: '导入成功',
        duration: 4
      });
      reload(gerRequestParames());
      uploadFileList.value = []
    } else {
      message.error(res.msg)
    }
  })
}
// 注册表格实例
/*const tableRef = ref()
function onRegisterTable(tableInstance: any) {
  registerTable(tableInstance);
  tableRef.value = tableInstance;

  // 同步获取表格数据
  const data = getDataSource();
  console.log('当前表格数据:', data);
}*/
// console.log('tabdata', getDataSource())
// 选中所有行
function selectAllRows() {
  if (!allchecked.value) {
    const allKeys = tableData.value.map(row => row.id);

    setSelectedRowKeys(allKeys);
  } else {
    clearSelectedRowKeys();
  }
}
// 跳转详情页
function goApplicationDetail(item: any) {
  console.log('route-----------------------', route)
  router.push({ path: '/applicationDetails/cvDetail', query: { id: item?.id } })
}
//所有的数据都从这里走的，点击时获取到对应的参数。放入state里

//通过Columns 获取state的options
function fuzzySearch(column, searchTerm: string = '') {
  // 将搜索词转换为小写，以便进行不区分大小写的比较
  const array = state.value[column.key].cacheOptions
  const lowerSearchTerm = searchTerm.toLowerCase();

  // 使用 filter 方法返回与搜索词匹配的项
  return array.filter(item => {
    // 将 label 转换为小写，并检查是否包含搜索词
    return item.label.toLowerCase().includes(lowerSearchTerm);
  });
}
const getColumns = (column, searchText: string = '') => {

  //获取筛选的数据选项
  // cacheOptions
  const list: any = [];
  tableData.value.forEach((el) => {
    if (searchText) {
      if (el[column.key].toUpperCase().includes(searchText.toUpperCase())) {
        list.push({
          label: el[column.key],
          value: el.key,
        });
      }
    } else {
      if (typeof (column) == 'string') {
        list.push({
          label: el[column],
          value: el.key,
        });

      } else {
        list.push({
          label: el[column.key],
          value: el.key,
        });
      }

    }
  });
  return list;
};
// 表格排序请求
const sortingFields = ref([])
const sortChange = (column, value, confirm) => {
  state.value[column.key].sort = value
  if (sortingFields.value.length > 0) {
    const list = sortingFields.value.filter(item => item.field === column.field)
    if (list.length > 0) {
      if (list[0].order === value) {
        sortingFields.value = sortingFields.value.filter(item => item.field !== column.field)
        state.value[column.key].sort = ''
      } else {
        list[0].order = value
      }
    } else {
      sortingFields.value.push({
        field: column.field,
        order: value,
        key: column.key
      })
    }
  } else {
    sortingFields.value.push({
      field: column.field,
      order: value,
      key: column.key
    })
  }
  diyRequestData.value = {
    sortingFields: sortingFields.value.map(item => {
      return {
        field: item.field,
        order: item.order
      }
    }),
  }
  reload();
}
// 输入框搜索
const keyWords = ref('')
const searchKeyWords = (e) => {
  // 通过自定义请求参数进行接口请求
  delete diyRequestData.value.keyWords
  diyRequestData.value = {
    keyWords: keyWords.value,
    ...diyRequestData.value
  }
  reload();
}
const focusFalg = ref<boolean>(false)
const handleBlur = (item) => {
  setTimeout(() => {
    if (!focusFalg.value) {
      item.showHistory = false;
    }
  }, 100);
}
const handleFocus = (item) => {
  focusFalg.value = false
  item.showHistory = true;
  const list = JSON.parse(localStorage.getItem(item.key) || '[]')
  item.historyList = list.slice(0, 5)
}

const removeHistory = (item, v) => {
  focusFalg.value = true
  item.historyList = item.historyList.filter(el => el !== v);
  console.log(item.historyList, 'item.historyList');
  localStorage.setItem(item.key, JSON.stringify(item.historyList))
}
//点击确定
const handleSearch = (selectedKeys, confirm, column) => {
  column.showHistory = false
  focusFalg.value = false
  if (column.history && state.value[column.key].inputValue) {
    column.historyList.unshift(state.value[column.key].inputValue);
    localStorage.setItem(column.key, JSON.stringify([...new Set(column.historyList)].slice(0, 5)))
  }
  // 表头下拉框确认事件
  confirm();
  // 通过全局缓存表头表单数据进行结果查询 并且展示出已选结果
  getResult(column);
  // 更新表格数据
  gerRequestParames()
  reload(gerRequestParames());
  console.log('刷新完成')
};
//获取筛选
const getResult = (column) => {
  const current = state.value[column.key];
  const checkedList = current.checkedList;
  if (column.formType === 'select') {
    state.value[column.key].requestValueList = checkedList
  } else if (column.formType === 'input') {
    state.value[column.key].requestValue = current.inputValue
  } else if (column.formType === 'timeRange') {
    state.value[column.key].requestValue = current.timeRange
  }
  const options = current.options;
  let result: any = [];
  if (checkedList?.length > 0) {
    options.forEach((el: any) => {
      checkedList.forEach((item) => {
        if (el.value === item) {
          result.push(el.label);
        }
      });
    });
  }
  let isExistedRow = resultList.value.find((el) => el.key == column.key);
  if (checkedList?.length === 0 && isExistedRow) {
    resultList.value = resultList.value.filter((el) => el.key != column.key);
    return;
  }
  const resStr = column.formType === 'select' ? (result.length > 3 ? result?.slice(0, 3).join('、') + ' 等' : result.join('、')) :
    column.formType === 'input' ? current.inputValue : current.timeRange.join('-')
  const finalMap = {
    label: column.title,
    key: column.key,
    value: `${column.title}：${resStr}`,
  };
  if (isExistedRow) {
    isExistedRow.value = finalMap.value;
  } else if (!isExistedRow && resStr) {
    resultList.value.push(finalMap);
  }
};
//输入框改变时
const handleInputChange = (event, column) => {
  let searchText = event.target.value;
  state.value[column.key].options = fuzzySearch(column, searchText);
};
// 多选按钮触发
const onCheckChange = (columns) => {
  if (state.value[columns.key].checkedList.length && (state.value[columns.key].checkedList.length === state.value[columns.key].options.length)) {
    state.value[columns.key].checkAll = true
  } else {
    state.value[columns.key].checkAll = false
  }
}
//全选的时候获取参数
const onCheckAllChange = (column) => {
  state.value[column.key].indeterminate = false;
  if (state.value[column.key].checkAll) {
    const options = state.value[column.key].options;
    state.value[column.key].checkedList = options.map((el) => el.value);
  } else {
    state.value[column.key].checkedList = [];
    console.log('走了yyyyyy')
  }
};
//取消全选的时候
const handleReset = (column) => {
  if (column.formType === 'select') {
    state.value[column.key].checkAll = false;
    state.value[column.key].indeterminate = false;
    state.value[column.key].checkedList = [];
  } else if (column.formType === 'input') {
    state.value[column.key].inputValue = ''
  } else {
    state.value[column.key].timeRange = []
  }
};
//标签页清空所有的参数
const removeAll = () => {
  radiogroupValue.value = ""
  filterRequestData.value = {  //清除左侧异常的筛选
    abnormal: null,
    isRepeated: null,
    isRecommends: null,
  }
  resultList.value.forEach((item) => {
    state.value[item.key].checkedList = [];
    state.value[item.key].indeterminate = false;
    state.value[item.key].checkAll = false;
    state.value[item.key].indeterminate = false;
    state.value[item.key].checkedList = [];
    state.value[item.key].inputValue = '';
    state.value[item.key].timeRange = [];
    state.value[item.key].requestValueList = [];
    state.value[item.key].requestValue = '';
  });
  if (sortingFields.value.length > 0) {
    sortingFields.value.forEach(item => {
      state.value[item.key].sort = '';
    })
  }
  resultList.value = [];
  diyRequestData.value = {}
  keyWords.value = ''
  sortingFields.value = []
  // 更新表格数据
  reload(gerRequestParames());
};
// 删除已选结果
const remove = (item) => {
  if (state.value[item.key].formType === 'input') {
    state.value[item.key].requestValue = '';
    state.value[item.key].inputValue = '';
  } else if (state.value[item.key].formType === 'time') {
    state.value[item.key].timeRange = [];
  } else {
    state.value[item.key].checkedList = [];
  }
  state.value[item.key].indeterminate = false;
  resultList.value = resultList.value.filter((v) => v.key !== item.key);
  reload()
};

//批量线下面试
const offlineInterviews = () => {
  let selects = getSelectRows();
  if (selects.length > 0) {
    statusLoading.value = true
    const list = selects.map(item => item.id)
    getOfflineInterviewTypeList(list);
    allchecked.value = false
  } else {
    message.error('你还没选择数据');
  }
}

const batchPass = () => {
  let selects = getSelectRows();
  if (selects.length > 0) {
    statusLoading.value = true
    batchPassResume(selects);
    allchecked.value = false

  } else {
    message.error('你还没选择数据');
  }
}
//取消面试
const getOnlineInterviewType = async (list: Object) => {
  console.log(list, 'list')
  const temp = { resumeId: list.id, operator: userInFor.userName }
  const data = await onlineInterviewType(temp)
  if (data && data.code === '10000') {
    message.success("操作成功")
    reload()
  } else {
    message.error(data.msg)
  }
}
//批量通过的接口
const batchPassResume = async (list) => {
  const param = {
    result: "通过",
    operator: userInFor.userName,
    applicationProcessSubmitRequests: list.map(el => {
      return {
        resumeId: el.id,
        processId: el.processId,
        educationType: el.educationType
      }
    })
  }
  console.log(param);
  const data = await batchResumeProgress(param).finally(() => {
    statusLoading.value = false
  });
  if (data && data.code === '10000') {
    message.success("操作成功")
    reload()
  } else {
    message.error(data.msg)
  }
}
// 线下面试接口
const getOfflineInterviewTypeList = async (list) => {
  const temp = { resumesIds: list, operator: userInFor.userName }
  const data = await offlineInterviewTypeList(temp)
  statusLoading.value = false
  if (data && data.code === '10000') {
    message.success("操作成功")
    reload()
  } else {
    message.error(data.msg)
  }
}

//选中所有的
function toggleSelectAll() {
  if (!isAllSelected.value) {
    // 如果要全选，但因为是单选逻辑，你可能只是想要高亮显示所有项
    selectedIndex.value = -1; // 假设我们“选中”了第一个
    isAllSelected.value = true;
  }
}
//选中某一项
function selectStage(index: number) {
  selectedIndex.value = index;
  isAllSelected.value = false;
}
//选中某一项状态
function statusSelect(item: any) {
  statusIndex.value = item.value;
}
const { userName } = store.userInFor
const pass = async (item) => {
  const { id, processId } = item  //props.process;
  const data = await resumeProgress({
    resumeId: id,
    processId: processId,
    result: "通过",
    reason: "",
    operator: userName
  });
  console.log(data)
  if (data && data.code == '10000') {
    message.success('更新成功');
    reload()
  } else {
    message.error(data.msg)
  }
}

const dieOut = async (item) => {
  const { id, processId } = item
  const data = await resumeProgress({
    resumeId: id,
    processId: processId,
    result: "淘汰",
    reason: "",
    operator: userName
  })
  if (data && data.code == '10000') {
    message.success('更新成功')
    reload()
  } else {
    message.error(data.msg)
  }
}
const uploadConfirm = async () => {
  if (uploadFileList.value.length === 0) {
    return message.error("请选择文件")
  }
  const file = uploadFileList.value[0].originFileObj;
  const name = getSuffix(file.name);
  if (name !== 'csv' && name !== 'xlsx') {
    return message.error("请上传.xlsx,.csv结尾的文件")
  }
  const formData = new FormData();
  formData.append('file', file);
  fileUpResumesList(file)
}

const downloadTemplate = () => {
  loading.value = true
  downloadFile('https://fangtian.work/get/url/application/email/校招一键导入简历模板(终版).xlsx', '简历模板.xlsx')
  loading.value = false
}
// 封装
function downloadFile(url, name) {
  url = url || ''
  name = name || ''
  let ele = document.createElement('a') as HTMLAnchorElement;
  ele.href = url
  ele.download = name
  ele.click()
  ele.parentNode?.removeChild(ele);
}

// 调用


</script>
<style lang="less" scoped>
:deep(.ant-col label) {
  &::before {
    content: "*";
    color: red;
    margin-right: 4px;
  }
}

:deep(::-webkit-scrollbar) {
  width: 8px;
  /* 滚动条宽度 */
  height: 8px !important;
  /* 滚动条高度 */
}

:deep(::-webkit-scrollbar-thumb:hover) {
  background-color: #dddddd !important;
  /* 鼠标悬停时滚动条拇指颜色 */
}


.item-render {
  background: rgba(32, 158, 228, 0.1);
  border-radius: 3px 3px 3px 3px;
  padding: 0 8px;
  box-sizing: border-box;
  color: #209EE4 !important;
  display: flex;
  justify-content: space-between;
  margin-top: 12px;
  height: 30px;
  line-height: 30px;
}

#applicationList {
  .main-content {
    padding: 16px;
    background-color: #FFFFFF;
    border-radius: 10px;

    .search {
      // display: flex;
      // align-items: center;
      // justify-content: space-between;
      margin-bottom: 8px;

      .titles {
        color: #333333;

        .title {
          font-size: 20px;
          font-weight: bold;
          margin-right: 16px;
        }

        .update {
          margin-left: 10px;
          color: #209EE4;
          cursor: pointer;

          &:hover {
            text-decoration-line: underline;
          }
        }
      }

      .search-r {
        margin-top: 10px;
        display: flex;
        gap: 0 8px;
        width: 100%;
        // flex-direction: row-reverse;
        justify-content: space-between;

        .search-input {
          width: 368px;
          height: 32px;
          border-radius: 3px;
          border: 1px solid rgba(179, 192, 200, 0.3);
          color: #B3C0C8;

          ::placeholder {
            color: #B3C0C8;
            font-weight: 400;

          }

          .search-i-i {
            width: 20px;
            height: 20px;
            cursor: pointer;
          }
        }

        .search-b-r {
          margin-right: 8px;
          // &:nth-of-type(1) {
          //   margin: 0 8px;
          //   margin-left: 9px;
          //   background-color: #FFFFFF;
          //   color: #B3C0C8;
          // }

          .search-i-r {
            border-radius: 3px;
            margin-right: 4px;
          }
        }

        .f-r-r {
          display: flex;
          flex-direction: row-reverse;
        }
      }
    }

    .filter {
      display: flex;
      flex-wrap: wrap;
      width: 100%;

      .filters-item {
        flex: 0 1 calc((100% - (6 * 17px)) / 7);
        margin-right: 17px;
        margin-bottom: 24px;

        &:nth-of-type(7n) {
          margin-right: 0;
        }
      }
    }
  }
}

:deep(.boxGroup) {
  display: flex;
  flex-direction: column;
}

.bottom_table {
  position: relative;
  background: #ffffff;

  .table_btnC {
    display: flex;
    align-items: baseline;
    position: absolute;
    bottom: -12px;
    left: 0px;
    height: 40px;
  }

  .result-wrap {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 10px;
    align-items: center;
    line-height: 30px;
    //background: #fff;
    border-radius: 4px;

    .result-item {
      flex: 1;
      font-size: 12px;
      margin-right: 15px;
      border: 1px solid #ccc;
      padding: 3px 10px;
      border-radius: 4px;
      box-sizing: border-box;
    }

    .result-clear {
      color: #209ee4;
      cursor: pointer;
      font-size: 14px;
      border: 1px solid;
      padding: 1px 5px;
    }
  }
}

.user-name {
  color: #209EE4;
  cursor: pointer;

  &:hover {
    text-decoration-line: underline;
  }
}

.status-name {
  width: 18px;
  height: 18px;
  border-radius: 3px;
  display: inline-block;
  font-size: 11px;
  text-align: center;
  line-height: 18px;
  margin-right: 5px;

}

.child1 {
  color: #FF4242 !important;
  background: rgba(255, 66, 66, 0.1) !important;

  :deep(.ant-radio-inner) {
    background: #FF4242;
    border-color: #FF4242
  }
}

.child2 {
  color: #F0A03D !important;
  background: rgba(240, 160, 61, 0.1) !important;

  :deep(.ant-radio-inner) {
    background: #F0A03D;
    border-color: #F0A03D
  }
}

.child3 {
  color: #209EE4 !important;
  background: rgba(32, 158, 228, 0.1) !important;

  :deep(.ant-radio-inner) {
    background: #209EE4;
    border-color: #209EE4
  }
}

.graduate {
  color: #209EE4;
  border: none;
  background-color: rgba(32, 158, 228, 0.15);
}

.graduate-other {
  color: #F0A03D;
  background-color: rgba(240, 160, 61, 0.15);

  &:hover {
    color: #F0A03D;
  }
}

.interview {
  color: #209EE4;
  background: rgba(32, 158, 228, 0.1);
}

.interview-other {
  color: #16C716;
  background: rgba(22, 199, 22, 0.1);
}

.filter-dropdown {
  padding: 8px;
  min-height: 50px;
  max-height: 300px;
  overflow-x: auto;
  box-sizing: border-box;

  .reset-top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16px;

    .reset-input {
      height: 32px;
      width: 140px;
    }
  }
}

.reset-btn {
  border: 1px solid rgba(179, 192, 200, 0.3) !important;
  margin-left: 10px;
}

.prevent {
  pointer-events: none;
  color: #ccc !important;
}

.history-wrap {
  background: #FFFFFF;
  margin-top: 4px;
  box-shadow: 0px 0px 4px 0px rgba(4, 50, 75, 0.3);
  border-radius: 4px 4px 4px 4px;
  padding: 5px 17px;
  box-sizing: border-box;

  .history-wrap-item {
    cursor: pointer;
    height: 30px;
    line-height: 30px;
    font-size: 14px;
    color: #333;
    display: flex;
    justify-content: space-between;

    .history-wrap-close {
      display: block;
    }

    &:hover {
      color: #209ee4;

      .history-wrap-close {
        display: block;
      }
    }
  }
}

.download-btn {
  position: absolute;
  top: 20px;
  right: 10px;
  cursor: pointer;
}

.upload-dragger {
  margin-top: 38px;
  margin-bottom: 30px;
}

.abnormal {
  display: flex;
  align-items: center;

  .abnormal-item {
    width: 82px;
    height: 32px;
    flex: 1;
    cursor: pointer;
    font-size: 16px;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 14px 0;
    box-sizing: border-box;
    border-radius: 16px;
    background-color: #F5F7FB;
    color: #333;
  }
}
</style>
